//
//
// SHMLogAdapter.C
//

#include "SHMLogAdapter.h"
#include "Exception.h"
#include "StrStream.h"
#include <iostream>

static SHMLogAdapter __SHM_ADAPTER_INST;

// 4k buffer
#define SHMSZ (4096*1024)
#define LOGSIZE 512

SHMLogAdapter::SHMLogAdapter(void) : _bOpened(false), _shmid(0), _shm(NULL)
{
	pHeader = NULL;
}

SHMLogAdapter::~SHMLogAdapter()
{}

bool SHMLogAdapter::Open(key_t key)
{
	if ((_shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0)
	{
		Util::StrStream str;
		str << "Error shmget " << ", " << strerror(errno);
		throw Exception(str);
	}

	 if ((_shm = (char*)shmat(_shmid, NULL, 0)) == (char *) -1) 
	 {
		 Util::StrStream str;
		 str << "Error shmat " << ", " << strerror(errno);
		 throw Exception(str);
	 }

	 pHeader = (ShmLogBufHeader*)_shm;
	 pHeader->_logCount = 0;
	 pHeader->_current = _shm + sizeof(ShmLogBufHeader);


	 return true;
}

bool SHMLogAdapter::Close(void)
{
	return true;
}

void SHMLogAdapter::Flush(void)
{}

void SHMLogAdapter::Report(void)
{}


bool SHMLogAdapter::Log(const std::string& info)
{

	/*
	pHeader->_current += LOGSIZE;
	if(pHeader->_current == _shm + SHMSZ)
		pHeader->_current = _shm;

	//memcpy(pHeader->_current, info.c_str(), info.size() + 1);
	memcpy(pHeader->_current, NULL, info.size() + 1);
	pHeader->_logCount++;

	*/


	return true;
}

LogManager::ADAPTER_TYPE SHMLogAdapter::AdapterType(void)
{
	return LogManager::SHMLOG_ADAPTER_TYPE;
}

